package com.biu.billiards.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biu.billiards.model.bo.BilliardsBO;
import com.biu.billiards.model.entity.Billiards;
import com.biu.billiards.mapper.BilliardsMapper;
import com.biu.billiards.model.entity.Device;
import com.biu.billiards.model.entity.Hardware;
import com.biu.billiards.model.vo.billiards.AddBilliardsVo;
import com.biu.billiards.model.vo.billiards.GetBilliardsVo;
import com.biu.billiards.model.vo.billiards.UpdateBilliardsVO;
import com.biu.billiards.model.vo.device.UpdateDeviceVO;
import com.biu.billiards.model.vo.mqtt.OpenBilliardsVo;
import com.biu.billiards.model.vo.mqtt.OpenDeviceVo;
import com.biu.billiards.mqqts.MqttService;
import com.biu.billiards.service.IBilliardsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biu.billiards.service.IDeviceService;
import com.biu.billiards.service.IHardwareService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xue
 * @since 2023-09-25
 */
@Service
public class BilliardsServiceImpl extends ServiceImpl<BilliardsMapper, Billiards> implements IBilliardsService {

//    @Autowired
//    private MqttMessageSender mqttMessageSender;


    @Resource
    private BilliardsMapper billiardsMapper;


    @Resource
    private IDeviceService deviceService;

    @Resource
    private IHardwareService hardwareService;



    @Autowired
    private MqttService mqttService;

    @Override
    public Boolean getBilliardsStatus(Integer id) {

        QueryWrapper<Billiards> query = new QueryWrapper<>();
        query.eq("shop_id",id);
        List<Billiards> billiardsList = billiardsMapper.selectList(query);

        Integer index = 0;

        for (Billiards billiards:billiardsList){
            if (billiards.getBilliardsStatus()==1){
                index+=1;
            }
        }

        if (index==0){
            return false;
        }else {
            return true;
        }


    }

    @Override
    public Boolean getBilliardsStatusClose(Integer shopId, String[] id) {
        QueryWrapper<Billiards> query = new QueryWrapper<>();
        query.eq("shop_id",shopId);

        List<Billiards>  list = billiardsMapper.selectList(query);

       int idNumber=0;

        for (Billiards billiards:list){
            for (String ids:id){
                if (billiards.getBilliardsId().toString().equals(ids) && billiards.getBilliardsStatus()==0){

//                    System.out.println(id);
//                    System.out.println("对对订单");
//                    isTrue=true;

                    idNumber+=1;

                }

            }

        }


        return idNumber==id.length;
    }

    @Override
    public Boolean getBilliardsStatusOpen(Integer shopIp,String[] id) {

        QueryWrapper<Billiards> query = new QueryWrapper<>();
        query.eq("shop_id",shopIp);

        List<Billiards>  list = billiardsMapper.selectList(query);

        for (Billiards billiards:list){
            for (String ids:id){
                if (billiards.getBilliardsId().toString().equals(ids) && billiards.getBilliardsStatus()==1){
                    return true;
                }
            }

        }


        return false;
    }

    @Override
    public Boolean getBilliardsOpenStatus(Integer id) {

        QueryWrapper<Billiards> query = new QueryWrapper<>();
        query.eq("billiards_id",id);

       Billiards billiards = billiardsMapper.selectOne(query);


        return billiards.getBilliardsStatus()==1;
    }

    @Override
    public Boolean openDevice(OpenDeviceVo openDeviceVo) {


        UpdateDeviceVO updateDeviceVO = new UpdateDeviceVO();
        updateDeviceVO.setDeviceId(openDeviceVo.getDeviceId());

        //    发送mqtt
        String msg;
        String no = String.format("%02d", openDeviceVo.getNumber());

        if (openDeviceVo.getOpen()==1) {

            msg = "{\"A"+no+"\":110000,\"res\":\"123\"}";
            updateDeviceVO.setStatus(1);

        }else {
            msg = "{\"A"+no+"\":100000,\"res\":\"1223\"}";
            updateDeviceVO.setStatus(0);
        }

       // getSubHardware

        //hardwareId
        String sub =  hardwareService.getSubHardware(openDeviceVo.getHardwareId());

        System.out.println(openDeviceVo);
        System.out.println("openDeviceVo123123123123");

        System.out.println(sub);

        deviceService.updateDevice(updateDeviceVO);

        mqttService.publish(msg,sub);


      //  mqttMessageSender.send("/corx/sub/CORX00001000",msg);



        return true;
    }




    @Override
    public Boolean openBilliards(OpenBilliardsVo openBilliardsVo)  {

        System.out.println("openBilliardsVo");
        System.out.println(openBilliardsVo);

        String msg;
        String no = String.format("%02d", openBilliardsVo.getDeviceNumber());

        UpdateBilliardsVO updateBilliardsVO = new UpdateBilliardsVO();
        updateBilliardsVO.setBilliardsId(openBilliardsVo.getBilliardsId());

        if (openBilliardsVo.getOpen()==1){
            updateBilliardsVO.setStartTime(LocalDateTime.now());
            updateBilliardsVO.setEndTime(LocalDateTime.now().plusHours(openBilliardsVo.getHour()));
            msg = "{\"A"+no+"\":110000,\"res\":\"123\"}";


        }else {

            updateBilliardsVO.setStartTime(null);
            updateBilliardsVO.setEndTime(null);

            System.out.println("asdasfasfasffas");
            msg = "{\"A"+no+"\":100000,\"res\":\"1223\"}";

        }
        updateBilliardsVO.setBilliardsStatus(openBilliardsVo.getOpen());
        updateBilliards(updateBilliardsVO);


       // Hardware hardware =  hardwareService.getSubHardware(openBilliardsVo.getShopId());

       String sub = hardwareService.getSubHardware(openBilliardsVo.getHardwareId());

        if (sub!=null){

            mqttService.publish(msg,sub);

        }



//        if (openBilliardsVo.getOpen()==1){
//
//            Thread delayedThread = new Thread(() -> {
//                try {
//                    System.out.println("开始任务11");
//                    // Delay for three seconds (3000 milliseconds)
//                    Thread.sleep(500);
//                    // Your task to be executed after the delay
//                    deviceService.autoOpenVrv(openBilliardsVo.getShopId());
//                } catch (InterruptedException e) {
//                    // Handle the InterruptedException (if needed)
//                    e.printStackTrace();
//                }
//            });
//
//            delayedThread.start();
//
//        }else {
//
//
//            Thread delayedThread = new Thread(() -> {
//                try {
//
//
//                    System.out.println("开始任务222");
//                    // Delay for three seconds (3000 milliseconds)
//                    Thread.sleep(500);
//                    // Your task to be executed after the delay
//                    deviceService.autoCloseVrv(openBilliardsVo.getShopId());
//                } catch (InterruptedException e) {
//                    // Handle the InterruptedException (if needed)
//                    e.printStackTrace();
//                }
//            });
//
//            delayedThread.start();
//        }


        return true;

    }



    public Boolean openBilliards2(List<OpenBilliardsVo> openBilliardsVoList,String deviceId)  {

        String msg = "{";

        for (OpenBilliardsVo openBilliardVo :openBilliardsVoList){


            String no = String.format("%02d", openBilliardVo.getDeviceNumber());

            UpdateBilliardsVO updateBilliardsVO = new UpdateBilliardsVO();
            updateBilliardsVO.setBilliardsId(openBilliardVo.getBilliardsId());

            if (openBilliardVo.getOpen()==1){
                updateBilliardsVO.setStartTime(LocalDateTime.now());
                updateBilliardsVO.setEndTime(LocalDateTime.now().plusHours(openBilliardVo.getHour()));
              //  msg = "{\"A"+no+"\":110000,\"res\":\"123\"}";
                msg=msg+"\"A"+no+"\":110000,";


            }else {

                updateBilliardsVO.setStartTime(null);
                updateBilliardsVO.setEndTime(null);

                System.out.println("asdasfasfasffas");
               // msg = "{\"A"+no+"\":100000,\"res\":\"1223\"}";
                msg=msg+"\"A"+no+"\":100000,";

            }
            updateBilliardsVO.setBilliardsStatus(openBilliardVo.getOpen());
            updateBilliards(updateBilliardsVO);

            // Hardware hardware =  hardwareService.getSubHardware(openBilliardsVo.getShopId());




//            if (openBilliardVo.getOpen()==1){
//
//                Thread delayedThread = new Thread(() -> {
//                    try {
//                        System.out.println("开始任务11");
//                        // Delay for three seconds (3000 milliseconds)
//                        Thread.sleep(500);
//                        // Your task to be executed after the delay
//                        deviceService.autoOpenVrv(openBilliardVo.getShopId());
//                    } catch (InterruptedException e) {
//                        // Handle the InterruptedException (if needed)
//                        e.printStackTrace();
//                    }
//                });
//
//                delayedThread.start();
//
//            }else {
//
//
//                Thread delayedThread = new Thread(() -> {
//                    try {
//
//
//                        System.out.println("开始任务222");
//                        // Delay for three seconds (3000 milliseconds)
//                        Thread.sleep(500);
//                        // Your task to be executed after the delay
//                        deviceService.autoCloseVrv(openBilliardVo.getShopId());
//                    } catch (InterruptedException e) {
//                        // Handle the InterruptedException (if needed)
//                        e.printStackTrace();
//                    }
//                });
//
//                delayedThread.start();
//            }



        }

        msg=msg+"\"res\":\"5123\"}";

        String sub = hardwareService.getSubHardware(deviceId);

        mqttService.publish(msg,sub);







        return true;

    }

    @Override
    public Boolean openBilliardsList(List<OpenBilliardsVo> openBilliardsVoLis) {


       // List<OpenDeviceVo> openDeviceVoList = new ArrayList<>();



        Map<String, List<OpenBilliardsVo>> groupedByShopId = new HashMap<>();

        for (OpenBilliardsVo openBilliardVo : openBilliardsVoLis) {
            String device = openBilliardVo.getHardwareId();

            // 如果 Map 中已存在该 shopId，则将对象添加到对应的列表中；否则，创建新的列表
            groupedByShopId.computeIfAbsent(device, k -> new ArrayList<>()).add(openBilliardVo);
        }

        // 打印分组结果
        groupedByShopId.forEach((device, group) -> {

            openBilliards2(group,device);

        });












        return null;
    }


    @Override
    public List<BilliardsBO> getBilliardsList(GetBilliardsVo getBilliardsVo) {

        QueryWrapper<Billiards> query = new QueryWrapper<>();

        if (getBilliardsVo.getShopId()!=null){
            query.eq("shop_id",getBilliardsVo.getShopId());
        }

        List<BilliardsBO> billiardsBOS = new ArrayList<>();
        List<Billiards> billiardsList = billiardsMapper.selectList(query);
        for (Billiards billiards: billiardsList){
            BilliardsBO adminDetailBO = new BilliardsBO();
            BeanUtils.copyProperties(billiards,adminDetailBO);
            billiardsBOS.add(adminDetailBO);
        }
        return billiardsBOS;
    }


    @Override
    public IPage<BilliardsBO> getBilliardsPage(GetBilliardsVo getBilliardsVo) {

        QueryWrapper<Billiards> query = new QueryWrapper<>();

        if (getBilliardsVo.getShopId()!=null){
            query.like("shop_id",getBilliardsVo.getShopId());
        }


        //新建分页条件
        Page<Billiards> p = new Page<>(getBilliardsVo.getCurrentPage(),getBilliardsVo.getPageSize());
        IPage<Billiards> userIPage = billiardsMapper.selectPage(p,query);
        IPage<BilliardsBO> page = new Page<>();
        List<BilliardsBO> adminDetailBOList = new ArrayList<>();
        for (Billiards admin: userIPage.getRecords()){
            BilliardsBO adminDetailBO = new BilliardsBO();
            BeanUtils.copyProperties(admin,adminDetailBO);
            adminDetailBOList.add(adminDetailBO);
        }
        /* 将转化的BO放到的Records里面  */
        page.setRecords(adminDetailBOList);
        page.setCurrent(userIPage.getCurrent());
        page.setPages(userIPage.getPages());
        page.setPages(userIPage.getSize());
        page.setTotal(userIPage.getTotal());
        return page;
    }

    @Override
    public Boolean updateBilliards(UpdateBilliardsVO updateBilliardsVO) {

        System.out.println("updateBilliardsVO");
        System.out.println(updateBilliardsVO);

        QueryWrapper<Billiards> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("billiards_id",updateBilliardsVO.getBilliardsId());

        Billiards billiards = billiardsMapper.selectOne(queryWrapper);
        billiards.setStartTime(updateBilliardsVO.getStartTime());
        billiards.setEndTime(updateBilliardsVO.getEndTime());
        billiards.setBilliardsStatus(updateBilliardsVO.getBilliardsStatus());
        billiards.setBilliardsNumber(updateBilliardsVO.getBilliardsNumber());
        billiards.setDeviceNumber(updateBilliardsVO.getDeviceNumber());
        billiards.setHardwareId(updateBilliardsVO.getHardwareId());
        billiards.setType(updateBilliardsVO.getType());
        billiards.setName(updateBilliardsVO.getName());

        return billiardsMapper.update(billiards, queryWrapper) == 1;
    }

    @Override
    public Boolean addBilliards(AddBilliardsVo addBilliardsVo) {

        Billiards billiards = new Billiards();

        System.out.println("addBilliardsVo");
        System.out.println(addBilliardsVo);

        BeanUtils.copyProperties(addBilliardsVo,billiards);
        billiards.setBilliardsId(null);

        System.out.println(billiards);
        return billiardsMapper.insert(billiards) == 1;

    }

    @Override
    public Boolean deleteBilliards(Integer billiardsId) {
        QueryWrapper<Billiards> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("billiards_id",billiardsId);
        return billiardsMapper.delete(queryWrapper) == 1;
    }


}
